package v1

import (
	"context"
	"encoding/base64"
	"fmt"
	"net/http"
	"regexp"
	"slices"
	"strings"
	"time"

	"github.com/golang-jwt/jwt/v5"
	"github.com/google/cel-go/cel"
	"github.com/labstack/echo/v4"
	"github.com/pkg/errors"
	"golang.org/x/crypto/bcrypt"
	expr "google.golang.org/genproto/googleapis/api/expr/v1alpha1"
	"google.golang.org/genproto/googleapis/api/httpbody"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	"google.golang.org/protobuf/encoding/protojson"
	"google.golang.org/protobuf/proto"
	"google.golang.org/protobuf/types/known/emptypb"
	"google.golang.org/protobuf/types/known/timestamppb"

	"quipus/internal/database/model"
	"quipus/internal/utils"
	v1pb "quipus/proto/gen/api/v1"
	apb "quipus/proto/gen/assist"
	cpb "quipus/proto/gen/common"
)

func (s *APIV1Service) ListUsers(ctx context.Context, request *v1pb.ListUsersRequest) (*v1pb.ListUsersResponse, error) {
	currentUser, err := s.GetCurrentUser(ctx)
	if err != nil {
		return nil, status.Errorf(codes.Internal, "failed to get user: %v", err)
	}

	userFind := &apb.FindUser{}

	if request.Filter != "" {
		filter, err := parseSearchUsersFilter(request.Filter)

		if err != nil {
			return nil, status.Errorf(codes.InvalidArgument, "invalid filter: %v", err)
		}

		if filter.Username != nil {
			userFind.Username = *filter.Username
		}
		if filter.Random {
			userFind.Random = true
		}
		if filter.Limit != nil {
			userFind.Limit = int32(*filter.Limit)
		}
		if filter.Email != nil {
			userFind.Email = *filter.Email
		}
		if filter.Nickname != nil {
			userFind.Nickname = *filter.Nickname
		}
		if filter.Role != nil {
			userFind.Role = cpb.Role(cpb.Role_value[*filter.Role])
		}
		if filter.Limit != nil {
			userFind.Limit = int32(*filter.Limit)
		}

		if filter.TenantUrn != nil {
			tenantID, err := utils.ExtractIDFromUrn(utils.TenantUrnPrefix, *filter.TenantUrn)
			if err != nil {
				return nil, status.Errorf(codes.InvalidArgument, "invalid tenant urn: %v", err)
			}

			if currentUser.Role == cpb.Role_TENANT_ADMIN.String() {
				if tenantID != currentUser.TenantID {
					return nil, status.Errorf(codes.PermissionDenied, "permission denied")
				}
			}
			userFind.TenantId = tenantID
		}
	}

	if currentUser.Role == cpb.Role_TENANT_ADMIN.String() {
		userFind.TenantId = currentUser.TenantID
	}

	if currentUser.Role == cpb.Role_USER.String() {
		userFind.CreatorId = currentUser.ID
		userFind.TenantId = currentUser.TenantID
	}

	var limit, offset int32
	if request.PageToken != nil {
		limit = request.PageToken.Limit
		offset = request.PageToken.Offset
	} else {
		limit = request.PageSize
	}

	if limit <= 0 {
		limit = DefaultPageSize
	}
	userFind.Limit = limit
	userFind.Offset = offset
	users, totalSize, err := s.Gds.Handler.ListUsers(ctx, userFind)
	if err != nil {
		return nil, status.Errorf(codes.Internal, "failed to list users: %v", err)
	}

	response := &v1pb.ListUsersResponse{
		TotalSize: int32(totalSize),
		Users:     []*v1pb.User{},
	}
	userMap := make(map[int32]*v1pb.User)

	for _, user := range users {
		uMsg := s.convertUserFromStore(user)
		tuser := userMap[user.CreatorID]
		if tuser == nil {
			u, _ := s.Gds.Handler.GetUser(ctx, &apb.FindUser{Id: user.CreatorID})
			if u == nil {
				continue
			}
			tuser = s.convertUserFromStore(u)

			if err != nil {
				return nil, errors.Wrap(err, "failed to convert user")
			}
		}
		uMsg.Creator = tuser
		userMap[user.CreatorID] = tuser
		response.Users = append(response.Users, uMsg)
	}
	return response, nil
}

func (s *APIV1Service) GetUser(ctx context.Context, request *v1pb.GetUserRequest) (*v1pb.User, error) {
	userID, err := utils.ExtractIDFromUrn(utils.UserUrnPrefix, request.Urn)
	if err != nil {
		return nil, status.Errorf(codes.InvalidArgument, "invalid user name: %v", err)
	}

	user, err := s.Gds.Handler.GetUser(ctx, &apb.FindUser{
		Id: userID,
	})

	if err != nil {
		return nil, status.Errorf(codes.Internal, "failed to get user: %v", err)
	}
	if user == nil {
		return nil, status.Errorf(codes.NotFound, "user not found")
	}

	return s.convertUserFromStore(user), nil
}

func (s *APIV1Service) GetUserAvatarBinary(ctx context.Context, request *v1pb.GetUserAvatarBinaryRequest) (*httpbody.HttpBody, error) {
	userID, err := utils.ExtractIDFromUrn(utils.UserUrnPrefix, request.Urn)
	if err != nil {
		return nil, status.Errorf(codes.InvalidArgument, "invalid user name: %v", err)
	}
	user, err := s.Gds.Handler.GetUser(ctx, &apb.FindUser{
		Id: userID,
	})
	if err != nil {
		return nil, status.Errorf(codes.Internal, "failed to get user: %v", err)
	}
	if user == nil {
		return nil, status.Errorf(codes.NotFound, "user not found")
	}
	if user.AvatarURL == "" {
		return nil, status.Errorf(codes.NotFound, "avatar not found")
	}

	imageType, base64Data, err := extractImageInfo(user.AvatarURL)
	if err != nil {
		return nil, status.Errorf(codes.Internal, "failed to extract image info: %v", err)
	}
	imageData, err := base64.StdEncoding.DecodeString(base64Data)
	if err != nil {
		return nil, status.Errorf(codes.Internal, "failed to decode string: %v", err)
	}
	httpBody := &httpbody.HttpBody{
		ContentType: imageType,
		Data:        imageData,
	}
	return httpBody, nil
}

func (s *APIV1Service) CreateUser(ctx context.Context, request *v1pb.CreateUserRequest) (*v1pb.User, error) {
	currentUser, err := s.GetCurrentUser(ctx)
	if err != nil {
		return nil, status.Errorf(codes.Internal, "failed to get user: %v", err)
	}

	if (request.Role == cpb.Role_ADMIN || request.Role == cpb.Role_TENANT_ADMIN) && currentUser.Role != cpb.Role_HOST.String() {
		return nil, status.Errorf(codes.PermissionDenied, "permission denied")
	}

	if request.Role == cpb.Role_USER && currentUser.Role != cpb.Role_TENANT_ADMIN.String() {
		return nil, status.Errorf(codes.InvalidArgument, "permission denied")
	}

	if !utils.UIDMatcher.MatchString(strings.ToLower(request.Username)) {
		return nil, status.Errorf(codes.InvalidArgument, "invalid username: %s", request.Username)
	}

	user := &model.User{
		Username:     request.Username,
		Role:         request.Role.String(),
		Email:        request.Email,
		Nickname:     request.Nickname,
		PasswordHash: "xxxxxxx",
	}

	if request.Password != nil {
		passwordHash, err := bcrypt.GenerateFromPassword([]byte(*request.Password), bcrypt.DefaultCost)
		if err != nil {
			return nil, echo.NewHTTPError(http.StatusInternalServerError, "failed to generate password hash").SetInternal(err)
		}
		user.PasswordHash = string(passwordHash)
	}

	if request.Visibility != nil {
		user.Visibility = request.Visibility.String()
	}

	if request.TenantUrn != "" {
		tenantID, err := utils.ExtractIDFromUrn(utils.TenantUrnPrefix, request.TenantUrn)
		if err != nil {
			return nil, status.Errorf(codes.InvalidArgument, "invalid tenant name: %v", err)
		}
		if (request.Role == cpb.Role_TENANT_ADMIN && tenantID != currentUser.TenantID) || (request.Role == cpb.Role_ADMIN && currentUser.Role != cpb.Role_HOST.String()) {
			return nil, status.Errorf(codes.PermissionDenied, "permission denied")
		}
		tenant, err := s.Gds.Handler.GetTenant(ctx, &apb.FindTenant{Id: tenantID})
		if err != nil {
			return nil, status.Errorf(codes.Internal, "failed to get tenant: %v", err)
		}

		user.TenantID = tenantID
		suffix := utils.TenantSuffix(tenant.TenantName)
		if !strings.HasSuffix(user.Username, suffix) {
			user.Username = utils.BuildMemberName(user.Username, tenant.TenantName)
		}
	}

	err = s.Gds.Handler.CreateUser(ctx, user)
	if err != nil {
		return nil, status.Errorf(codes.Internal, "failed to create user: %v", err)
	}

	return s.convertUserFromStore(user), nil
}

func (s *APIV1Service) CreateVirtUser(ctx context.Context, request *v1pb.CreateUserRequest) (*v1pb.User, error) {
	currentUser, err := s.GetCurrentUser(ctx)
	if err != nil {
		return nil, status.Errorf(codes.Internal, "failed to get user: %v", err)
	}

	if request.Role != cpb.Role_AI_ASSISTANT {
		return nil, status.Errorf(codes.InvalidArgument, "permission denied")
	}

	if !utils.UIDMatcher.MatchString(strings.ToLower(request.Username)) {
		return nil, status.Errorf(codes.InvalidArgument, "invalid username: %s", request.Username)
	}

	user := &model.User{
		Username:     request.Username,
		Role:         request.Role.String(),
		Email:        request.Email,
		Nickname:     request.Nickname,
		PasswordHash: "xxxxxxx",
		TenantID:     currentUser.TenantID,
		CreatorID:    currentUser.ID,
	}

	if request.Visibility != nil {
		user.Visibility = request.Visibility.String()
	}

	err = s.Gds.Handler.CreateUser(ctx, user)
	if err != nil {
		return nil, status.Errorf(codes.Internal, "failed to create user: %v", err)
	}

	return s.convertUserFromStore(user), nil
}

func (s *APIV1Service) UpdatePassword(ctx context.Context, request *v1pb.UpdatePasswordRequest) (*emptypb.Empty, error) {
	userID, err := utils.ExtractIDFromUrn(utils.UserUrnPrefix, request.Urn)
	if err != nil {
		return nil, status.Errorf(codes.InvalidArgument, "invalid user name: %v", err)
	}

	currentUser, err := s.GetCurrentUser(ctx)
	if err != nil {
		return nil, status.Errorf(codes.Internal, "failed to get user: %v", err)
	}

	if currentUser.ID != userID && currentUser.Role != cpb.Role_ADMIN.String() && currentUser.Role != cpb.Role_HOST.String() {
		return nil, status.Errorf(codes.PermissionDenied, "permission denied")
	}

	if err := bcrypt.CompareHashAndPassword([]byte(currentUser.PasswordHash), []byte(request.OldPassword)); err != nil {
		return nil, status.Errorf(codes.InvalidArgument, "unmatched old password")
	}

	passwordHash, err := bcrypt.GenerateFromPassword([]byte(request.NewPassword), bcrypt.DefaultCost)
	if err != nil {
		return nil, echo.NewHTTPError(http.StatusInternalServerError, "failed to generate password hash").SetInternal(err)
	}

	passwordHashStr := string(passwordHash)
	currentTs := time.Now().Unix()
	update := &apb.UpdateUser{
		Id:           userID,
		UpdatedTs:    currentTs,
		PasswordHash: passwordHashStr,
	}

	_, err = s.Gds.Handler.UpdateUser(ctx, update)
	if err != nil {
		return nil, status.Errorf(codes.Internal, "failed to update user: %v", err)
	}

	return nil, nil
}

func (s *APIV1Service) UpdateUser(ctx context.Context, request *v1pb.UpdateUserRequest) (*v1pb.User, error) {
	userID, err := utils.ExtractIDFromUrn(utils.UserUrnPrefix, request.User.Urn)
	if err != nil {
		return nil, status.Errorf(codes.InvalidArgument, "invalid user name: %v", err)
	}
	currentUser, err := s.GetCurrentUser(ctx)
	if err != nil {
		return nil, status.Errorf(codes.Internal, "failed to get user: %v", err)
	}

	if currentUser.ID != userID && currentUser.Role != cpb.Role_ADMIN.String() && currentUser.Role != cpb.Role_HOST.String() {
		return nil, status.Errorf(codes.PermissionDenied, "permission denied")
	}

	if request.UpdateMask == nil || len(request.UpdateMask.Paths) == 0 {
		return nil, status.Errorf(codes.InvalidArgument, "update mask is empty")
	}

	user, err := s.Gds.Handler.GetUser(ctx, &apb.FindUser{Id: userID})
	if err != nil {
		return nil, status.Errorf(codes.Internal, "failed to get user: %v", err)
	}
	if user == nil {
		return nil, status.Errorf(codes.NotFound, "user not found")
	}

	currentTs := time.Now().Unix()
	update := &apb.UpdateUser{
		Id:        user.ID,
		UpdatedTs: currentTs,
	}

	for _, field := range request.UpdateMask.Paths {
		if field == "nickname" {
			update.Nickname = request.User.Nickname
		} else if field == "email" {
			update.Email = request.User.Email
		} else if field == "avatar_url" {
			update.Avatar = request.User.Avatar
		} else if field == "description" {
			update.Description = request.User.Description
		} else if field == "role" {
			update.Role = request.User.Role
		} else if field == "row_status" {
			update.RowStatus = request.User.RowStatus
		} else {
			return nil, status.Errorf(codes.InvalidArgument, "invalid update path: %s", field)
		}
	}

	_, err = s.Gds.Handler.UpdateUser(ctx, update)
	if err != nil {
		return nil, status.Errorf(codes.Internal, "failed to update user: %v", err)
	}

	userUpdated, err := s.Gds.Handler.GetUser(ctx, &apb.FindUser{Id: userID})
	if err != nil {
		return nil, status.Errorf(codes.Internal, "failed to get user: %v", err)
	}
	return s.convertUserFromStore(userUpdated), nil
}

func (s *APIV1Service) UpdateVirt(ctx context.Context, request *v1pb.UpdateUserRequest) (*v1pb.User, error) {
	userID, err := utils.ExtractIDFromUrn(utils.UserUrnPrefix, request.User.Urn)
	if err != nil {
		return nil, status.Errorf(codes.InvalidArgument, "invalid user name: %v", err)
	}
	currentUser, err := s.GetCurrentUser(ctx)
	if err != nil {
		return nil, status.Errorf(codes.Internal, "failed to get user: %v", err)
	}

	if request.UpdateMask == nil || len(request.UpdateMask.Paths) == 0 {
		return nil, status.Errorf(codes.InvalidArgument, "update mask is empty")
	}

	user, err := s.Gds.Handler.GetUser(ctx, &apb.FindUser{Id: userID})
	if err != nil {
		return nil, status.Errorf(codes.Internal, "failed to get user: %v", err)
	}
	if user == nil {
		return nil, status.Errorf(codes.NotFound, "user not found")
	}

	if user.Role != cpb.Role_AI_ASSISTANT.String() {
		return nil, status.Errorf(codes.PermissionDenied, "target is not ai assistant, permission denied")
	}

	if user.CreatorID != currentUser.ID {
		return nil, status.Errorf(codes.PermissionDenied, "creator not match, permission denied")
	}

	currentTs := time.Now().Unix()
	update := &apb.UpdateUser{
		Id:        user.ID,
		UpdatedTs: currentTs,
	}

	for _, field := range request.UpdateMask.Paths {
		if field == "nickname" {
			update.Nickname = request.User.Nickname
		} else if field == "email" {
			update.Email = request.User.Email
		} else if field == "avatar" {
			update.Avatar = request.User.Avatar
		} else if field == "description" {
			update.Description = request.User.Description
		} else if field == "username" {
			update.Username = request.User.Username
		} else {
			return nil, status.Errorf(codes.InvalidArgument, "invalid update path: %s", field)
		}
	}

	_, err = s.Gds.Handler.UpdateUser(ctx, update)
	if err != nil {
		return nil, status.Errorf(codes.Internal, "failed to update user: %v", err)
	}

	userUpdated, err := s.Gds.Handler.GetUser(ctx, &apb.FindUser{Id: userID})
	if err != nil {
		return nil, status.Errorf(codes.Internal, "failed to get user: %v", err)
	}
	return s.convertUserFromStore(userUpdated), nil
}

func (s *APIV1Service) DeleteUser(ctx context.Context, request *v1pb.DeleteUserRequest) (*emptypb.Empty, error) {
	userID, err := utils.ExtractIDFromUrn(utils.UserUrnPrefix, request.Urn)
	if err != nil {
		return nil, status.Errorf(codes.InvalidArgument, "invalid user name: %v", err)
	}
	currentUser, err := s.GetCurrentUser(ctx)
	if err != nil {
		return nil, status.Errorf(codes.Internal, "failed to get user: %v", err)
	}
	if currentUser.ID != userID && currentUser.Role != cpb.Role_ADMIN.String() && currentUser.Role != cpb.Role_HOST.String() && currentUser.Role != cpb.Role_TENANT_ADMIN.String() {
		return nil, status.Errorf(codes.PermissionDenied, "permission denied")
	}

	user, err := s.Gds.Handler.GetUser(ctx, &apb.FindUser{Id: userID})
	if err != nil {
		return nil, status.Errorf(codes.Internal, "failed to get user: %v", err)
	}
	if user == nil {
		return nil, status.Errorf(codes.NotFound, "user not found")
	}

	if currentUser.Role == cpb.Role_TENANT_ADMIN.String() && currentUser.TenantID != user.TenantID {
		return nil, status.Errorf(codes.PermissionDenied, "permission denied")
	}

	if user.Role == cpb.Role_AI_ASSISTANT.String() {
		s.Gds.Handler.DeleteVirtUser(ctx, user.ID)
	}

	s.Gds.Handler.DeleteKnot(ctx, &apb.DeleteKnot{
		CreatorId: user.ID})

	if err := s.Gds.Handler.DeleteUser(ctx, &apb.DeleteUser{
		Id: user.ID,
	}); err != nil {
		return nil, status.Errorf(codes.Internal, "failed to delete user: %v", err)
	}

	return &emptypb.Empty{}, nil
}

func (s *APIV1Service) DeleteVirt(ctx context.Context, request *v1pb.DeleteUserRequest) (*emptypb.Empty, error) {
	userID, err := utils.ExtractIDFromUrn(utils.UserUrnPrefix, request.Urn)
	if err != nil {
		return nil, status.Errorf(codes.InvalidArgument, "invalid user name: %v", err)
	}

	currentUser, err := s.GetCurrentUser(ctx)
	if err != nil {
		return nil, status.Errorf(codes.Internal, "failed to get user: %v", err)
	}

	user, err := s.Gds.Handler.GetUser(ctx, &apb.FindUser{Id: userID})
	if err != nil {
		return nil, status.Errorf(codes.Internal, "failed to get user: %v", err)
	}

	if user == nil {
		return nil, status.Errorf(codes.NotFound, "user not found")
	}

	if user.CreatorID != currentUser.ID {
		return nil, status.Errorf(codes.PermissionDenied, "permission denied")
	}

	if user.Role != cpb.Role_AI_ASSISTANT.String() {
		return nil, status.Errorf(codes.PermissionDenied, "permission denied")
	}

	if err := s.Gds.Handler.DeleteUser(ctx, &apb.DeleteUser{
		Id: user.ID,
	}); err != nil {
		return nil, status.Errorf(codes.Internal, "failed to delete user: %v", err)
	}

	return &emptypb.Empty{}, nil
}

func getDefaultUserSetting() *v1pb.UserSetting {
	return &v1pb.UserSetting{
		Locale:         "cn",
		Appearance:     "system",
		KnotVisibility: "PRIVATE",
	}
}

func (s *APIV1Service) GetUserSetting(ctx context.Context, _ *v1pb.GetUserSettingRequest) (*v1pb.UserSetting, error) {
	user, err := s.GetCurrentUser(ctx)
	if err != nil {
		return nil, status.Errorf(codes.Internal, "failed to get current user: %v", err)
	}

	userSettings, err := s.Gds.Handler.ListUserSettings(ctx, user.ID)
	if err != nil {
		return nil, status.Errorf(codes.Internal, "failed to list user settings: %v", err)
	}
	userSettingMessage := getDefaultUserSetting()
	for _, setting := range userSettings {
		if setting.Key == apb.UserSettingKey_LOCALE.String() {
			userSettingMessage.Locale = setting.Value
		} else if setting.Key == apb.UserSettingKey_APPEARANCE.String() {
			userSettingMessage.Appearance = setting.Value
		} else if setting.Key == apb.UserSettingKey_KNOT_VISIBILITY.String() {
			userSettingMessage.KnotVisibility = setting.Value
		}
	}

	return userSettingMessage, nil
}

func (s *APIV1Service) UpdateUserSetting(ctx context.Context, request *v1pb.UpdateUserSettingRequest) (*v1pb.UserSetting, error) {
	user, err := s.GetCurrentUser(ctx)
	if err != nil {
		return nil, status.Errorf(codes.Internal, "failed to get current user: %v", err)
	}

	if request.UpdateMask == nil || len(request.UpdateMask.Paths) == 0 {
		return nil, status.Errorf(codes.InvalidArgument, "update mask is empty")
	}

	for _, field := range request.UpdateMask.Paths {
		if field == "locale" {
			if err := s.Gds.Handler.UpsertUserSetting(ctx, &model.UserSetting{
				UserID: user.ID,
				Key:    apb.UserSettingKey_LOCALE.String(),
				Value:  request.Setting.Locale,
			}); err != nil {
				return nil, status.Errorf(codes.Internal, "failed to upsert user setting: %v", err)
			}
		} else if field == "appearance" {
			if err := s.Gds.Handler.UpsertUserSetting(ctx, &model.UserSetting{
				UserID: user.ID,
				Key:    apb.UserSettingKey_APPEARANCE.String(),
				Value:  request.Setting.Appearance,
			}); err != nil {
				return nil, status.Errorf(codes.Internal, "failed to upsert user setting: %v", err)
			}
		} else if field == "knot_visibility" {
			if err := s.Gds.Handler.UpsertUserSetting(ctx, &model.UserSetting{
				UserID: user.ID,
				Key:    apb.UserSettingKey_KNOT_VISIBILITY.String(),
				Value:  request.Setting.KnotVisibility,
			}); err != nil {
				return nil, status.Errorf(codes.Internal, "failed to upsert user setting: %v", err)
			}
		} else {
			return nil, status.Errorf(codes.InvalidArgument, "invalid update path: %s", field)
		}
	}

	return s.GetUserSetting(ctx, &v1pb.GetUserSettingRequest{})
}

func (s *APIV1Service) ListUserAccessTokens(ctx context.Context, request *v1pb.ListUserAccessTokensRequest) (*v1pb.ListUserAccessTokensResponse, error) {
	userID, err := utils.ExtractIDFromUrn(utils.UserUrnPrefix, request.Urn)
	if err != nil {
		return nil, status.Errorf(codes.InvalidArgument, "invalid user name: %v", err)
	}

	currentUser, err := s.GetCurrentUser(ctx)
	if err != nil {
		return nil, status.Errorf(codes.Internal, "failed to get current user: %v", err)
	}
	if currentUser == nil {
		return nil, status.Errorf(codes.PermissionDenied, "permission denied")
	}
	if currentUser.ID != userID {
		return nil, status.Errorf(codes.PermissionDenied, "permission denied")
	}

	userAccessTokens, err := s.Gds.Handler.GetUserAccessTokens(ctx, userID)
	if err != nil {
		return nil, status.Errorf(codes.Internal, "failed to list access tokens: %v", err)
	}

	accessTokens := []*v1pb.UserAccessToken{}
	for _, userAccessToken := range userAccessTokens {
		claims := &ClaimsMessage{}
		_, err := jwt.ParseWithClaims(userAccessToken.AccessToken, claims, func(t *jwt.Token) (any, error) {
			if t.Method.Alg() != jwt.SigningMethodHS256.Name {
				return nil, errors.Errorf("unexpected access token signing method=%v, expect %v", t.Header["alg"], jwt.SigningMethodHS256)
			}
			if kid, ok := t.Header["kid"].(string); ok {
				if kid == "v1" {
					return []byte(s.Secret), nil
				}
			}
			return nil, errors.Errorf("unexpected access token kid=%v", t.Header["kid"])
		})
		if err != nil {
			// If the access token is invalid or expired, just ignore it.
			continue
		}

		userAccessToken := &v1pb.UserAccessToken{
			AccessToken: userAccessToken.AccessToken,
			Description: userAccessToken.Description,
			IssuedAt:    timestamppb.New(claims.IssuedAt.Time),
		}
		if claims.ExpiresAt != nil {
			userAccessToken.ExpiresAt = timestamppb.New(claims.ExpiresAt.Time)
		}
		accessTokens = append(accessTokens, userAccessToken)
	}

	// Sort by issued time in descending order.
	slices.SortFunc(accessTokens, func(i, j *v1pb.UserAccessToken) int {
		return int(i.IssuedAt.Seconds - j.IssuedAt.Seconds)
	})
	response := &v1pb.ListUserAccessTokensResponse{
		AccessTokens: accessTokens,
	}
	return response, nil
}

func (s *APIV1Service) CreateUserAccessToken(ctx context.Context, request *v1pb.CreateUserAccessTokenRequest) (*v1pb.UserAccessToken, error) {
	userID, err := utils.ExtractIDFromUrn(utils.UserUrnPrefix, request.Urn)
	if err != nil {
		return nil, status.Errorf(codes.InvalidArgument, "invalid user name: %v", err)
	}
	currentUser, err := s.GetCurrentUser(ctx)
	if err != nil {
		return nil, status.Errorf(codes.Internal, "failed to get current user: %v", err)
	}
	if currentUser == nil {
		return nil, status.Errorf(codes.PermissionDenied, "permission denied")
	}
	if currentUser.ID != userID {
		return nil, status.Errorf(codes.PermissionDenied, "permission denied")
	}

	expiresAt := time.Time{}
	if request.ExpiresAt != nil {
		expiresAt = request.ExpiresAt.AsTime()
	}

	accessToken, err := GenerateAccessToken(currentUser.Username, currentUser.ID, expiresAt, []byte(s.Secret))
	if err != nil {
		return nil, status.Errorf(codes.Internal, "failed to generate access token: %v", err)
	}

	claims := &ClaimsMessage{}
	_, err = jwt.ParseWithClaims(accessToken, claims, func(t *jwt.Token) (any, error) {
		if t.Method.Alg() != jwt.SigningMethodHS256.Name {
			return nil, errors.Errorf("unexpected access token signing method=%v, expect %v", t.Header["alg"], jwt.SigningMethodHS256)
		}
		if kid, ok := t.Header["kid"].(string); ok {
			if kid == "v1" {
				return []byte(s.Secret), nil
			}
		}
		return nil, errors.Errorf("unexpected access token kid=%v", t.Header["kid"])
	})
	if err != nil {
		return nil, status.Errorf(codes.Internal, "failed to parse access token: %v", err)
	}

	// Upsert the access token to user setting apb.
	if err := s.UpsertAccessTokenToStore(ctx, currentUser, accessToken, request.Description); err != nil {
		return nil, status.Errorf(codes.Internal, "failed to upsert access token to store: %v", err)
	}

	userAccessToken := &v1pb.UserAccessToken{
		AccessToken: accessToken,
		Description: request.Description,
		IssuedAt:    timestamppb.New(claims.IssuedAt.Time),
	}
	if claims.ExpiresAt != nil {
		userAccessToken.ExpiresAt = timestamppb.New(claims.ExpiresAt.Time)
	}
	return userAccessToken, nil
}

func (s *APIV1Service) DeleteUserAccessToken(ctx context.Context, request *v1pb.DeleteUserAccessTokenRequest) (*emptypb.Empty, error) {
	userID, err := utils.ExtractIDFromUrn(utils.UserUrnPrefix, request.Urn)
	if err != nil {
		return nil, status.Errorf(codes.InvalidArgument, "invalid user name: %v", err)
	}
	currentUser, err := s.GetCurrentUser(ctx)
	if err != nil {
		return nil, status.Errorf(codes.Internal, "failed to get current user: %v", err)
	}
	if currentUser == nil {
		return nil, status.Errorf(codes.PermissionDenied, "permission denied")
	}
	if currentUser.ID != userID {
		return nil, status.Errorf(codes.PermissionDenied, "permission denied")
	}

	userAccessTokens, err := s.Gds.Handler.GetUserAccessTokens(ctx, currentUser.ID)
	if err != nil {
		return nil, status.Errorf(codes.Internal, "failed to list access tokens: %v", err)
	}
	updatedUserAccessTokens := []*apb.AccessTokensUserSetting_AccessToken{}
	for _, userAccessToken := range userAccessTokens {
		if userAccessToken.AccessToken == request.AccessToken {
			continue
		}
		updatedUserAccessTokens = append(updatedUserAccessTokens, userAccessToken)
	}

	token := &apb.AccessTokensUserSetting{
		AccessTokens: updatedUserAccessTokens,
	}

	b, e := proto.Marshal(token)
	if e != nil {
		return nil, status.Errorf(codes.Internal, "failed to marshal user setting: %v", e)
	}

	if err := s.Gds.Handler.UpsertUserSetting(ctx, &model.UserSetting{
		UserID: currentUser.ID,
		Key:    apb.UserSettingKey_ACCESS_TOKENS.String(),
		Value:  string(b),
	}); err != nil {
		return nil, status.Errorf(codes.Internal, "failed to upsert user setting: %v", err)
	}

	return &emptypb.Empty{}, nil
}

func (s *APIV1Service) UpsertAccessTokenToStore(ctx context.Context, user *model.User, accessToken, description string) error {
	userAccessTokens, err := s.Gds.Handler.GetUserAccessTokens(ctx, user.ID)
	if err != nil {
		return errors.Wrap(err, "failed to get user access tokens")
	}
	userAccessToken := apb.AccessTokensUserSetting_AccessToken{
		AccessToken: accessToken,
		Description: description,
	}

	upsertLogins := []*apb.AccessTokensUserSetting_AccessToken{}
	upserts := []*apb.AccessTokensUserSetting_AccessToken{}
	loginCount := int32(0)
	for _, t := range userAccessTokens {
		claims := &ClaimsMessage{}
		_, err := jwt.ParseWithClaims(t.AccessToken, claims, func(t *jwt.Token) (any, error) {
			if t.Method.Alg() != jwt.SigningMethodHS256.Name {
				return nil, status.Errorf(codes.Unauthenticated, "unexpected access token signing method=%v, expect %v", t.Header["alg"], jwt.SigningMethodHS256)
			}
			if kid, ok := t.Header["kid"].(string); ok {
				if kid == "v1" {
					return []byte(s.Secret), nil
				}
			}
			return nil, status.Errorf(codes.Unauthenticated, "unexpected access token kid=%v", t.Header["kid"])
		})

		if err != nil {
			continue
		}

		if t.AccessToken == accessToken {
			continue
		}

		if loginCount >= 5 {
			upsertLogins = upsertLogins[1:]
			loginCount -= 1
		}

		if t.Description == "user login" {
			upsertLogins = append(upsertLogins, t)
			loginCount += 1
		} else {
			upserts = append(upserts, t)
		}
	}

	if loginCount >= 1 {
		upserts = append(upserts, upsertLogins...)
	}

	upserts = append(upserts, &userAccessToken)

	tokens := &apb.AccessTokensUserSetting{
		AccessTokens: upserts,
	}

	b, e := protojson.Marshal(tokens)
	if e != nil {
		return status.Errorf(codes.Internal, "failed to marshal user setting: %v", e)
	}

	if err := s.Gds.Handler.UpsertUserSetting(ctx, &model.UserSetting{
		UserID: user.ID,
		Key:    apb.UserSettingKey_ACCESS_TOKENS.String(),
		Value:  string(b),
	}); err != nil {
		return errors.Wrap(err, "failed to upsert user setting")
	}
	return nil
}

func isSimpleFileName(name string) bool {
	// 1. 不包含路径分隔符
	if strings.Contains(name, "/") || strings.Contains(name, "\\") {
		return false
	}

	// 2. 不包含协议前缀
	if strings.Contains(name, "://") {
		return false
	}

	// 3. 包含文件扩展名（可选，根据需求决定是否需要）
	if !strings.Contains(name, ".") {
		return false
	}

	// 4. 文件名长度合理（可选）
	if len(name) > 255 {
		return false
	}

	return true
}

func (s *APIV1Service) convertUserFromStore(user *model.User) *v1pb.User {
	userpb := &v1pb.User{
		Urn:         utils.BuildUrn(utils.UserUrnPrefix, user.ID),
		Id:          user.ID,
		RowStatus:   cpb.RowStatus(cpb.RowStatus_value[user.RowStatus]),
		CreateTime:  timestamppb.New(time.Unix(user.CreatedTs, 0)),
		UpdateTime:  timestamppb.New(time.Unix(user.UpdatedTs, 0)),
		Role:        cpb.Role(cpb.Role_value[user.Role]),
		Username:    user.Username,
		Email:       user.Email,
		Nickname:    user.Nickname,
		Avatar:      user.AvatarURL,
		TenantUrn:   utils.BuildUrn(utils.TenantUrnPrefix, user.TenantID),
		Description: user.Description,
	}
	ctx := context.Background()
	tenant, err := s.Gds.Handler.GetTenant(ctx, &apb.FindTenant{Id: user.TenantID})
	if err != nil {
		return userpb
	}
	userpb.TenantName = tenant.TenantName

	userpb.Username, _ = utils.ExtractUser(userpb.Username)

	// Use the avatar URL instead of raw base64 image data to reduce the response size.
	if user.AvatarURL != "" {
		if isSimpleFileName(user.AvatarURL) {
			userpb.Avatar = fmt.Sprintf("/file/%s/avatar", userpb.Urn)
		}
	}

	v := cpb.Visibility(cpb.Visibility_value[user.Visibility])
	userpb.Visibility = &v
	return userpb
}

// SearchUsersFilterCELAttributes are the CEL attributes for SearchUsersFilter.
var SearchUsersFilterCELAttributes = []cel.EnvOption{
	cel.Variable("username", cel.StringType),
	cel.Variable("random", cel.BoolType),
	cel.Variable("limit", cel.IntType),
	cel.Variable("email", cel.StringType),
	cel.Variable("nickname", cel.StringType),
	cel.Variable("role", cel.StringType),
	cel.Variable("tenant", cel.StringType),
}

type SearchUsersFilter struct {
	Username  *string
	Random    bool
	Limit     *int
	TenantUrn *string

	Email    *string
	Nickname *string
	Role     *string
}

func parseSearchUsersFilter(expression string) (*SearchUsersFilter, error) {
	e, err := cel.NewEnv(SearchUsersFilterCELAttributes...)
	if err != nil {
		return nil, err
	}
	ast, issues := e.Compile(expression)
	if issues != nil {
		return nil, errors.Errorf("found issue %v", issues)
	}
	filter := &SearchUsersFilter{}
	expr, err := cel.AstToParsedExpr(ast)
	if err != nil {
		return nil, err
	}
	callExpr := expr.GetExpr().GetCallExpr()
	findSearchUsersField(callExpr, filter)
	return filter, nil
}

func findSearchUsersField(callExpr *expr.Expr_Call, filter *SearchUsersFilter) {
	if len(callExpr.Args) == 2 {
		idExpr := callExpr.Args[0].GetIdentExpr()
		if idExpr != nil {
			if idExpr.Name == "username" {
				username := callExpr.Args[1].GetConstExpr().GetStringValue()
				filter.Username = &username
			} else if idExpr.Name == "random" {
				random := callExpr.Args[1].GetConstExpr().GetBoolValue()
				filter.Random = random
			} else if idExpr.Name == "limit" {
				limit := int(callExpr.Args[1].GetConstExpr().GetInt64Value())
				filter.Limit = &limit
			} else if idExpr.Name == "tenant" {
				urn := callExpr.Args[1].GetConstExpr().GetStringValue()
				filter.TenantUrn = &urn
			} else if idExpr.Name == "role" {
				role := callExpr.Args[1].GetConstExpr().GetStringValue()
				filter.Role = &role
			}

			return
		}
	}
	for _, arg := range callExpr.Args {
		callExpr := arg.GetCallExpr()
		if callExpr != nil {
			findSearchUsersField(callExpr, filter)
		}
	}
}

func extractImageInfo(dataURI string) (string, string, error) {
	dataURIRegex := regexp.MustCompile(`^data:(?P<type>.+);base64,(?P<base64>.+)`)
	matches := dataURIRegex.FindStringSubmatch(dataURI)
	if len(matches) != 3 {
		return "", "", errors.New("Invalid data URI format")
	}
	imageType := matches[1]
	base64Data := matches[2]
	return imageType, base64Data, nil
}

func (s *APIV1Service) SetVirtUserAbility(ctx context.Context, request *v1pb.SetVirtUserRequest) (*v1pb.SetVirtUserResponse, error) {
	currentUser, err := s.GetCurrentUser(ctx)
	if err != nil {
		return nil, status.Errorf(codes.Internal, "failed to get user: %v", err)
	}

	userID, err := utils.ExtractIDFromUrn(utils.UserUrnPrefix, request.Urn)
	if err != nil {
		return nil, status.Errorf(codes.InvalidArgument, "invalid user name: %v", err)
	}

	user, err := s.Gds.Handler.GetUser(ctx, &apb.FindUser{
		Id: userID,
	})

	if user.Role != cpb.Role_AI_ASSISTANT.String() {
		return nil, status.Errorf(codes.PermissionDenied, "only AI assistant can set ability")
	}

	if user.CreatorID != currentUser.ID {
		return nil, status.Errorf(codes.PermissionDenied, "only creator can set ability")
	}

	if request.ArtifactUrn == "" {
		return nil, status.Errorf(codes.InvalidArgument, "artifact urn is required")
	}

	virt := &model.VirtUser{
		ID: userID,
	}

	if strings.HasPrefix(request.ArtifactUrn, utils.AssistantUrnPrefix) {
		id, err := utils.ExtractIDFromUrn(utils.AssistantUrnPrefix, request.ArtifactUrn)
		if err != nil {
			return nil, status.Errorf(codes.InvalidArgument, "invalid artifact urn: %v", err)
		}
		virt.VirtID = id
		virt.VirtType = v1pb.ArtifactType_ARTIFACT_ASSISTANT.String()
	} else if strings.HasPrefix(request.ArtifactUrn, utils.WorkflowUrnPrefix) {
		id, err := utils.ExtractIDFromUrn(utils.WorkflowUrnPrefix, request.ArtifactUrn)
		if err != nil {
			return nil, status.Errorf(codes.InvalidArgument, "invalid artifact urn: %v", err)
		}
		virt.VirtID = id
		virt.VirtType = v1pb.ArtifactType_ARTIFACT_WORKFLOW.String()
	} else {
		return nil, status.Errorf(codes.InvalidArgument, "invalid artifact urn: %v", err)
	}

	err = s.Gds.Handler.UpsertVirtUser(ctx, virt)
	if err != nil {
	}

	return nil, nil
}

func (s *APIV1Service) GetVirtUserAbility(ctx context.Context, request *v1pb.GetVirtUserRequest) (*v1pb.GetVirtUserResponse, error) {
	currentUser, err := s.GetCurrentUser(ctx)
	if err != nil {
		return nil, status.Errorf(codes.Internal, "failed to get user: %v", err)
	}

	userID, err := utils.ExtractIDFromUrn(utils.UserUrnPrefix, request.Urn)
	if err != nil {
		return nil, status.Errorf(codes.InvalidArgument, "invalid user name: %v", err)
	}

	user, err := s.Gds.Handler.GetUser(ctx, &apb.FindUser{
		Id: userID,
	})

	if user.Role != cpb.Role_AI_ASSISTANT.String() {
		return nil, status.Errorf(codes.PermissionDenied, "only AI assistant can set ability")
	}

	if user.CreatorID != currentUser.ID {
		return nil, status.Errorf(codes.PermissionDenied, "only creator can set ability")
	}
	virt, err := s.Gds.Handler.GetVirtUser(ctx, userID)
	if err != nil {

	}

	rsp := &v1pb.GetVirtUserResponse{
		Urn: request.Urn,
	}

	virtType := v1pb.ArtifactType(v1pb.ArtifactType_value[virt.VirtType])
	switch virtType {
	case v1pb.ArtifactType_ARTIFACT_ASSISTANT:
		rsp.ArtifactUrn = utils.BuildUrn(utils.AssistantUrnPrefix, virt.VirtID)
		break
	case v1pb.ArtifactType_ARTIFACT_WORKFLOW:
		rsp.ArtifactUrn = utils.BuildUrn(utils.WorkflowUrnPrefix, virt.VirtID)
		break
	default:
		return nil, status.Errorf(codes.Internal, "unknown virt type: %v", virtType)
	}

	if rsp.ArtifactUrn == "" {
		return nil, status.Errorf(codes.NotFound, "virt user not found")
	}

	return rsp, nil
}

func (s *APIV1Service) DeleteVirtUserAbility(ctx context.Context, request *v1pb.GetVirtUserRequest) (*emptypb.Empty, error) {
	currentUser, err := s.GetCurrentUser(ctx)
	if err != nil {
		return nil, status.Errorf(codes.Internal, "failed to get user: %v", err)
	}

	userID, err := utils.ExtractIDFromUrn(utils.UserUrnPrefix, request.Urn)
	if err != nil {
		return nil, status.Errorf(codes.InvalidArgument, "invalid user name: %v", err)
	}

	user, err := s.Gds.Handler.GetUser(ctx, &apb.FindUser{
		Id: userID,
	})

	if user.Role != cpb.Role_AI_ASSISTANT.String() {
		return nil, status.Errorf(codes.PermissionDenied, "only AI assistant can set ability")
	}

	if user.CreatorID != currentUser.ID {
		return nil, status.Errorf(codes.PermissionDenied, "only creator can set ability")
	}

	err = s.Gds.Handler.DeleteVirtUser(ctx, userID)
	return nil, err
}

func (s *APIV1Service) AttachVirtUser(ctx context.Context, request *v1pb.AttachVirtUserRequest) (*v1pb.AttachVirtUserResponse, error) {
	currentUser, err := s.GetCurrentUser(ctx)
	if err != nil {
		return nil, status.Errorf(codes.Internal, "failed to get user: %v", err)
	}

	userID, err := utils.ExtractIDFromUrn(utils.UserUrnPrefix, request.Urn)
	if err != nil {
		return nil, status.Errorf(codes.InvalidArgument, "invalid user name: %v", err)
	}

	if currentUser.ID != userID {
		return nil, status.Errorf(codes.PermissionDenied, "only creator can set ability")
	}

	attachId, err := utils.ExtractIDFromUrn(utils.UserUrnPrefix, request.AttachUrn)
	if err != nil {
		return nil, status.Errorf(codes.InvalidArgument, "invalid attach user name: %v", err)
	}

	user, err := s.Gds.Handler.GetUser(ctx, &apb.FindUser{
		Id:        attachId,
		CreatorId: currentUser.ID,
		Role:      cpb.Role_AI_ASSISTANT,
	})

	if err != nil {
		return nil, status.Errorf(codes.NotFound, "attach user not found")
	}

	if user == nil {
		return nil, status.Errorf(codes.NotFound, "attach ai assistant not found")
	}

	attach := &model.AttachUser{
		ID:         userID,
		AttachedID: attachId,
	}

	err = s.Gds.Handler.UpsertAttachUser(ctx, attach)
	if err != nil {
		return nil, err
	}

	updatedUser, err := s.Gds.Handler.UpdateUser(ctx, &apb.UpdateUser{Id: userID, RowStatus: cpb.RowStatus_ATTACHED})
	rsp := &v1pb.AttachVirtUserResponse{}
	rsp.Urn = request.Urn
	rsp.AttachUrn = request.AttachUrn
	rsp.User = s.convertUserFromStore(updatedUser)
	return rsp, err
}

func (s *APIV1Service) DetachVirtUser(ctx context.Context, request *v1pb.DetachVirtUserRequest) (*v1pb.DetachVirtUserResponse, error) {
	currentUser, err := s.GetCurrentUser(ctx)
	if err != nil {
		return nil, status.Errorf(codes.Internal, "failed to get user: %v", err)
	}

	if currentUser.RowStatus != cpb.RowStatus_ATTACHED.String() {
		return nil, status.Errorf(codes.PermissionDenied, "only attached user can detach")
	}

	userID, err := utils.ExtractIDFromUrn(utils.UserUrnPrefix, request.Urn)
	if err != nil {
		return nil, status.Errorf(codes.InvalidArgument, "invalid user name: %v", err)
	}

	if currentUser.ID != userID {
		return nil, status.Errorf(codes.PermissionDenied, "only creator can set ability")
	}

	err = s.Gds.Handler.DeleteAttachUser(ctx, userID)
	if err != nil {
		return nil, err
	}

	updatedUser, err := s.Gds.Handler.UpdateUser(ctx, &apb.UpdateUser{Id: userID, RowStatus: cpb.RowStatus_ATTACHED})
	rsp := &v1pb.DetachVirtUserResponse{}
	rsp.Urn = request.Urn
	rsp.User = s.convertUserFromStore(updatedUser)
	return rsp, err
}
